package com.googlecode.openauth.web.action;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;

import com.googlecode.openauth.web.config.CommonProperty;
import com.googlecode.openauth.web.dao.IRoleActionDao;
import com.googlecode.openauth.web.dao.IRoleDao;
import com.googlecode.openauth.web.dao.IUserDao;
import com.googlecode.openauth.web.dao.IUserRoleDao;
import com.googlecode.openauth.web.entity.ActionPageBean;
import com.googlecode.openauth.web.entity.RoleInfo;
import com.googlecode.openauth.web.entity.UserInfo;
import com.googlecode.openauth.web.entity.UserRole;
import com.googlecode.openauth.web.util.Util;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UsrAction extends ActionSupport {

	private static final long serialVersionUID = -8748287041583824834L;

	private int userId;
	private int[] userIds;
	private String username;
	private String password;
	private String corporateCode;
	private String address;
	private String phone;
	private String fax;
	private String description;
	private String email;
	private String idCard;
	private String registerIp;
	private Timestamp registerDate;
	private String userPoliceNo;
	private IUserDao usrDao;
	private List<UserInfo> list;
	private ActionPageBean<UserInfo> actionPageBean;
	private String oper = "list";
	private IUserRoleDao userRoleDao;
	private int currentPageNo = 1;
	private int prevPageNo = 1;
	private int nextPageNo = 1;
	private int totalCount = 0;
	private int pageNum = CommonProperty.PAGENUM;
	private int roleId;
	private int curRoleId;
	private IRoleActionDao roleActionDao;

	public IRoleActionDao getRoleActionDao() {
		return roleActionDao;
	}

	public void setRoleActionDao(IRoleActionDao roleActionDao) {
		this.roleActionDao = roleActionDao;
	}

	public int getCurRoleId() {
		return curRoleId;
	}

	public void setCurRoleId(int curRoleId) {
		this.curRoleId = curRoleId;
	}

	@Override
	public String execute() throws Exception {
		list = usrDao.getUsers(getUserFromForm());
		List<UserInfo> data = usrDao.getAllUser(getCurRole(), new RowBounds(0, pageNum));
		actionPageBean = new ActionPageBean<UserInfo>();
		actionPageBean.setData(data);
		return SUCCESS;
	}

	private UserInfo getCurUser() {
		ActionContext context = ActionContext.getContext();
		Map<String, Object> session = context.getSession();
		Object obj = session.get("user");
		UserInfo result = new UserInfo();
		result.setUserId(-1);
		if (obj == null) {
			return result;
		}

		if (!(obj instanceof UserInfo)) {
			return result;
		}

		result = (UserInfo) obj;
		return result;
	}

	private RoleInfo getCurRole() {
		RoleInfo result = new RoleInfo();
		result.setRoleId(-1);

		UserInfo userInfo = getCurUser();
		List<RoleInfo> roles = userInfo.getRoleInfos();

		if (roles == null || roles.isEmpty()) {
			return result;
		}

		result = roles.get(0);
		return result;
	}

	public String getNextPage() throws Exception {
		RoleInfo curRole = getCurRole();
		int totalCount = usrDao.getAllUserCount(curRole);
		actionPageBean = new ActionPageBean<UserInfo>();
		actionPageBean.setTotalCount(totalCount);

		ActionPageBean<UserInfo> pageBean = getPageBean();
		pageBean.setTotalCount(totalCount);
		Util util = new Util();
		RowBounds rowBounds = util.calcNextRowBounds(pageBean);
		setPageBean(pageBean);
		List<UserInfo> data = usrDao.getAllUser(curRole, rowBounds);
		actionPageBean.setData(data);
		return SUCCESS;
	}

	public String getPrevPage() throws Exception {
		RoleInfo curRole = getCurRole();
		int totalCount = usrDao.getAllUserCount(curRole);
		actionPageBean = new ActionPageBean<UserInfo>();
		actionPageBean.setTotalCount(totalCount);

		ActionPageBean<UserInfo> pageBean = getPageBean();
		pageBean.setTotalCount(totalCount);
		Util util = new Util();
		RowBounds rowBounds = util.calcPrevRowBounds(pageBean);
		setPageBean(pageBean);
		List<UserInfo> data = usrDao.getAllUser(curRole, rowBounds);
		actionPageBean.setData(data);
		return SUCCESS;
	}

	public String getFirstPage() throws Exception {
		RoleInfo curRole = getCurRole();
		int totalCount = usrDao.getAllUserCount(curRole);
		actionPageBean = new ActionPageBean<UserInfo>();
		actionPageBean.setTotalCount(totalCount);

		ActionPageBean<UserInfo> pageBean = getPageBean();
		pageBean.setTotalCount(totalCount);
		pageBean.setPrevPageNo(1);
		pageBean.setCurrentPageNo(1);
		Util util = new Util();
		int maxPageNo = util.getMaxPageNo(pageBean);
		if (maxPageNo <= 1) {
			pageBean.setNextPageNo(1);
		} else {
			pageBean.setNextPageNo(2);
		}

		int offset = 0;
		int limit = pageBean.getPageNum();
		RowBounds rowBounds = new RowBounds(offset, limit);
		setPageBean(pageBean);
		List<UserInfo> data = usrDao.getAllUser(curRole, rowBounds);
		actionPageBean.setData(data);
		return SUCCESS;
	}

	public String getLastPage() throws Exception {
		RoleInfo curRole = getCurRole();
		int totalCount = usrDao.getAllUserCount(curRole);
		actionPageBean = new ActionPageBean<UserInfo>();
		actionPageBean.setTotalCount(totalCount);

		ActionPageBean<UserInfo> pageBean = getPageBean();
		pageBean.setTotalCount(totalCount);
		Util util = new Util();
		int maxPageNo = util.getMaxPageNo(pageBean);
		pageBean.setCurrentPageNo(maxPageNo);
		pageBean.setNextPageNo(maxPageNo);

		if (maxPageNo <= 1) {
			pageBean.setPrevPageNo(1);
		} else {
			pageBean.setPrevPageNo(maxPageNo - 1);
		}
		int limit = pageBean.getPageNum();
		int offset = (maxPageNo - 1) * limit;
		RowBounds rowBounds = new RowBounds(offset, limit);
		setPageBean(pageBean);
		List<UserInfo> data = usrDao.getAllUser(curRole, rowBounds);
		actionPageBean.setData(data);
		return SUCCESS;
	}

	public String save() throws Exception {
		UserRole urole = new UserRole();
		if (oper.equals("save")) {
			UserInfo user = this.getUserFromForm();

			// 密码MD5加密
			String decodedPassword = user.getPassword();
			String encodedPassword = Util.encode(decodedPassword);
			user.setPassword(encodedPassword);

			usrDao.insertUser(user);
			int uid = (int) user.getUserId();
			urole.setRoleId(roleId);
			urole.setUserId(uid);
			this.userRoleDao.addUserRole(urole);
			resetForm();
			this.userId = 0;
			return "success";
		} else {
			usrDao.updateUser(this.getUserFromForm());
			urole.setRoleId(roleId);
			urole.setUserId(26);
			this.userRoleDao.updateUserRole(urole);
			resetForm();
			this.userId = 0;
			return "success";
		}

	}

	private List<RoleInfo> rlist;

	public List<RoleInfo> getRlist() {
		return rlist;
	}

	public void setRlist(List<RoleInfo> rlist) {
		this.rlist = rlist;
	}

	private IRoleDao roleDao;

	public IRoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(IRoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public String init() throws Exception {
		curRoleId = getCurRole().getRoleId();
		rlist = roleDao.getChildRoles(curRoleId);
		if (oper.equals("save")) {
			roleId = curRoleId;
			return "new";
		} else {
			UserInfo usr = usrDao.getUserById((int) userId);
			usr.setRoleId(userRoleDao.getUserRoleByUserId(userId).get(0)
					.getRoleId());
			setUserFromForm(usr);
			return "update";
		}
	}

	public String delete() throws Exception {
		userRoleDao.delUserRoleByUserId(userIds[0]);
		usrDao.deleteUser(userIds[0]);
		return SUCCESS;
	}

	public UserInfo getUserFromForm() {
		UserInfo usr = new UserInfo();
		curRoleId = getCurRole().getRoleId();
		usr.setRoleId(curRoleId);
		usr.setAddress(address);
		usr.setCorporateCode(corporateCode);
		usr.setDescription(description);
		usr.setEmail(email);
		usr.setFax(fax);
		usr.setIdCard(idCard);
		// 以md5方式存储,暂时默认123456
		usr.setPassword("123456");
		usr.setPhone(phone);
		usr.setRegisterDate(registerDate);
		usr.setRegisterIp(registerIp);
		usr.setUserId(userId);
		usr.setUsername(username);
		usr.setUserPoliceNo(userPoliceNo);
		return usr;
	}

	public void setUserFromForm(UserInfo usr) {
		address = usr.getAddress();
		corporateCode = usr.getCorporateCode();
		description = usr.getDescription();
		email = usr.getEmail();
		fax = usr.getFax();
		idCard = usr.getIdCard();
		password = usr.getPassword();
		phone = usr.getPhone();
		registerDate = usr.getRegisterDate();
		registerIp = usr.getRegisterIp();
		userId = (int) usr.getUserId();
		username = usr.getUsername();
		userPoliceNo = usr.getUserPoliceNo();
		roleId = usr.getRoleId();
	}

	public void resetForm() {
		address = "";
		corporateCode = "";
		description = "";
		email = "";
		fax = "";
		idCard = "";
		password = "";
		phone = "";
		registerDate = null;
		registerIp = "";
		userId = 0;
		username = "";
		userPoliceNo = "";
	}

	public int[] getUserIds() {
		return userIds;
	}

	public void setUserIds(int[] userIds) {
		this.userIds = userIds;
	}

	public String getOper() {
		return oper;
	}

	public void setOper(String oper) {
		this.oper = oper;
	}

	public List<UserInfo> getList() {
		return list;
	}

	public void setList(List<UserInfo> list) {
		this.list = list;
	}

	public IUserDao getUsrDao() {
		return usrDao;
	}

	public void setUsrDao(IUserDao usrDao) {
		this.usrDao = usrDao;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCorporateCode() {
		return corporateCode;
	}

	public void setCorporateCode(String corporateCode) {
		this.corporateCode = corporateCode;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getFax() {
		return fax;
	}

	public void setFax(String fax) {
		this.fax = fax;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getIdCard() {
		return idCard;
	}

	public void setIdCard(String idCard) {
		this.idCard = idCard;
	}

	public String getRegisterIp() {
		return registerIp;
	}

	public void setRegisterIp(String registerIp) {
		this.registerIp = registerIp;
	}

	public Timestamp getRegisterDate() {
		return registerDate;
	}

	public void setRegisterDate(Timestamp registerDate) {
		this.registerDate = registerDate;
	}

	public String getUserPoliceNo() {
		return userPoliceNo;
	}

	public void setUserPoliceNo(String userPoliceNo) {
		this.userPoliceNo = userPoliceNo;
	}

	// 取PageBean
	public ActionPageBean<UserInfo> getActionPageBean() {
		return actionPageBean;
	}

	public void setActionPageBean(ActionPageBean<UserInfo> actionPageBean) {
		this.actionPageBean = actionPageBean;
	}

	public ActionPageBean<UserInfo> getPageBean() {
		ActionPageBean<UserInfo> bean = new ActionPageBean<UserInfo>();
		bean.setCurrentPageNo(currentPageNo);
		bean.setPrevPageNo(prevPageNo);
		bean.setNextPageNo(nextPageNo);
		bean.setTotalCount(totalCount);
		bean.setPageNum(pageNum);
		return bean;
	}

	public void setPageBean(ActionPageBean<UserInfo> bean) {
		currentPageNo = bean.getCurrentPageNo();
		prevPageNo = bean.getPrevPageNo();
		nextPageNo = bean.getNextPageNo();
		totalCount = bean.getTotalCount();
	}

	// 取当前页号
	public int getCurrentPageNo() {
		return currentPageNo;
	}

	public void setCurrentPageNo(int currentPageNo) {
		this.currentPageNo = currentPageNo;
	}

	// 取上页页号
	public int getPrevPageNo() {
		return prevPageNo;
	}

	public void setPrevPageNo(int prevPageNo) {
		this.prevPageNo = prevPageNo;
	}

	// 取下页页号
	public int getNextPageNo() {
		return nextPageNo;
	}

	public void setNextPageNo(int nextPageNo) {
		this.nextPageNo = nextPageNo;
	}

	// 取总页号
	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public IUserRoleDao getUserRoleDao() {
		return userRoleDao;
	}

	public void setUserRoleDao(IUserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	public int getRoleId() {
		return roleId;
	}

	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}
}
